# -*- coding:utf-8 -*-
__author__ = u'Long Yuan'
import sys
import os
import re
import fnmatch

reload(sys)
sys.setdefaultencoding('utf-8')

re_file_ext1 = re.compile(r'.+\.java')
re_file_ext2 = re.compile(r'.+\.jsp')
re_file_ext3 = re.compile(r'.+\.js')



#利用os模块的walk进行遍历输出
def listMenu(menu, regex):
    match_files = []
    for path, dirs, files in os.walk(menu.encode('gbk')):
        print "PATH:", path
        for filename in files:
            filepath = os.path.join(path, filename).decode('gbk')
            if None != regex.match(filename):
                print '\t匹配：', filename
                match_files.append((path, filename))
            else:
                print '\t不匹配', filename
    return match_files


def matchFilenameReplace2MatchNewFilename(matchlist, regex, replace_str):
    for tuple2 in matchlist:
        old_fullpath = os.path.join(tuple2[0], tuple2[1]).decode('gbk')
        if os.path.isfile(old_fullpath):
            if re.match(regex, tuple2[1]):
                new_name = re.sub(regex, replace_str, tuple2[1])
                print new_name
                os.rename(old_fullpath, os.path.join(tuple2[0], new_name).decode('gbk'))


def matchFilecontentReplace2MatchNewFilecontent(matchlist, re_list):
    for tuple2 in matchlist:
        old_fullpath = os.path.join(tuple2[0], tuple2[1]).decode('gbk')
        print '正在在批量替换文件内容:\n\t[%s]' % old_fullpath

        # 使用fnmatch 模块来匹配文件名
        bool1 = fnmatch.fnmatch(old_fullpath, '*.js')
        bool2 = fnmatch.fnmatch(old_fullpath, '*.jsp')

        if bool1 or bool2:
            print '文件匹配，执行替换操作.'
            fileHandle = open(old_fullpath)
            newcontent = []
            try:
                allLines = fileHandle.readlines()
                for eachLine in allLines:
                    print '内容扫描:\t%s' % eachLine,
                    for res in re_list:
                        eachLine = eachLine.replace(res[0], res[1])

                        print '\t替换[%s]->[%s]:\t%s' % (res[0], res[1], eachLine),
                    print '替换完毕:\t%s' % eachLine,
                    newcontent.append(eachLine)

                print '文件内容：\n', ''.join(newcontent)
            finally:
                fileHandle.close()

            os.rename(old_fullpath, os.path.join(tuple2[0], os.path.join(tuple2[0], 'copy_' + tuple2[1]).decode('gbk')).decode('gbk'))

            newfilepath = old_fullpath
            newFileHandle = open(newfilepath,'w')
            try:
                newFileHandle.writelines(newcontent)
            finally:
                newFileHandle.close()




if __name__ == '__main__':
    FILEPATH = r'D:\\Workspace\\qm\\qmcrm\\bizplatform\\src\\main\\webapp\\biz\\voucher\\pdplan'
    re_filename = re.compile(r'production-plan')
    newfilename = r'production-plan'
    match_files = listMenu(FILEPATH, re_filename)

    re_list = (
        (r'biz/order/sale/sale-order', r'biz/voucher/pdplan/production-plan'),
        (r'saleOrder', r'productionPlan'),
        (r'SaleOrder', r'ProductionPlan'),
        (r'biz-sale-sale-order', r'biz-voucher-production-plan'),
        (r'销售', r'生产计划')
    )

    matchFilecontentReplace2MatchNewFilecontent(match_files, re_list)

    # matchFilenameReplace2MatchNewFilename(match_files,re_filename,newfilename)


